package cn.gok.web;

import cn.gok.service.StudentService;
import cn.gok.service.impl.StudentServiceImpl;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONUtil;
import cn.gok.util.R;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

//@WebServlet("/login")
public class StudentLoginServlet extends HttpServlet {
    private StudentService studentService = new StudentServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String studentName = req.getParameter("studentName");
        String password = req.getParameter("password");
        String verificationCode=req.getParameter("verificationCode");
        //产生验证码
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(116,36,4,20);
        String imageBase64=lineCaptcha.getImageBase64();
        //把验证码输出到前端
        lineCaptcha.write(resp.getOutputStream());
        //把验证码存到session
        req.getSession().setAttribute("code",lineCaptcha.getCode());



        R data = studentService.queryStudentByNameAndPassword(studentName, password);
        if (data.getCode() == 200){
            req.getSession().setAttribute("student", data.get("student"));
            System.out.println(data + "===========================");
        }

        String jsonStr = JSONUtil.toJsonStr(data);
        resp.getWriter().println(jsonStr);





//        StringBuffer requestURL = req.getRequestURL();
//        String queryString = req.getQueryString();
//        String method = req.getMethod();
        //重要的获取数据
      //  String name = req.getParameter("name");//zhangsan
      //  String[] names = req.getParameterValues("names");//zhangsan,lisi
        //请求转发,存
//        req.setAttribute("name","zhangsan");
//        req.setAttribute("age",20);
//        List<String > list=new ArrayList<>();
//        list.add("aaa");
//        list.add("nbb");
//        req.setAttribute("list",list);
//        req.getRequestDispatcher("/test").forward(req,resp);
//        //test里面取,或写在jsp里
//        String  name = (String) req.getAttribute("name");
//        Integer age = (Integer) req.getAttribute("age");
//        List<String > list1 = (List<String>) req.getAttribute("list");
        //字符流
//        PrintWriter writer = resp.getWriter();
//        writer.write("hello");
        //字节流
//        ServletOutputStream outputStream = resp.getOutputStream();
//        outputStream.write("hello".getBytes());
        //重定向,
       // resp.sendRedirect("test");
    }


}
